import React from 'react';
import { connect } from 'dva';
import { Buffer } from 'buffer';
import { Input, Modal, Popover, Form, Progress, message, Row, Col } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';
import styles from './UpdatePassword.less';
import { encryptedData } from '@/utils/utils';
import { publicKey } from '@/../public/global';
import { validateContinuousChar } from '@/utils/validator';
import { specicalChars } from '@/support/constant/common';

const FormItem = Form.Item;
const passwordStatusMap = {
  ok: <p className={styles.success}>强度：强</p>,
  pass: <p className={styles.warning}>强度：中</p>,
  pool: <p className={styles.error}>规则不匹配</p>,
  empty: <p className={styles.error}>不能为空</p>,
};

const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  pool: 'exception',
};
class updatePassword extends React.Component {
  formRef = React.createRef();
  state = {
    update: false,
    pwdStrategy: undefined,
    pwdStrategyDesc: undefined
  };
  componentWillUnmount() {
    clearInterval(this.interval);
  }

  componentDidMount() {
    this.getRegular();
  }

  getRegular = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'http/getData',
      payload: {
        url: '/passwordstrategy/getregular/default'
      },
      callback: (res) => {
        let { pwdStrategy, pwdStrategyDesc } = res.data || {}
        this.setState({
          pwdStrategy,
          pwdStrategyDesc
        })
      }
    });
  }

  getPasswordStatus = () => {
    this.formRef;
    if (!this.formRef.current) return;
    const {
      rdata: { pwdStrategy },
    } = this.props;
    const form = this.formRef.current;
    const value = form.getFieldValue('password');
    const regex = new RegExp(pwdStrategy);
    if (!value) {
      return 'empty';
    }
    if (value && regex.test(value) && value.length > 9) {
      return 'ok';
    }
    if (value && regex.test(value) && value.length > 5) {
      return 'pass';
    }
    return 'pool';
  };
  handleOk = e => {
    const { dispatch, oldPassword, accountName } = this.props;
    const form = this.formRef.current;
    e.preventDefault();
    form.validateFields().then(values => {
      const { dispatch } = this.props;
      const params = {
        accountName: encryptedData(accountName, publicKey),
        currentPwd: encryptedData(values.password, publicKey),
        originalPwd: encryptedData(oldPassword, publicKey),
      };
      dispatch({
        type: 'login/loginForceModifypwd',
        payload: params,
        callback: response => {
          if (response && response.statusCode === '0') {
            message.success('密码已修改，请重新登录');
            this.handleCancel();
          }
        },
      });
    });
  };
  handleCancel = () => {
    const { changeVisible, firstLogin, fetchCode } = this.props;
    const form = this.formRef.current;
    if (firstLogin) {
      message.error('第一次登录必须修改初始密码');
    } else {
      changeVisible();
      form.resetFields();
      fetchCode();
    }
  };
  checkPassword = (rule, value) => {
    const {
       pwdStrategy, pwdStrategyDesc
    } = this.state;
    const regex = new RegExp(pwdStrategy);
    
    if (!value) {
      return Promise.reject('请输入密码')
    } else {
      if (!regex.test(value)) {
        return Promise.reject(pwdStrategyDesc)
      }else if(/([\dA-Za-z])\1{3,}/.test(value)) {
        return Promise.reject('禁止密码设置4位连续相同的字符');
      } else if(validateContinuousChar(value)) {
        return Promise.reject('禁止密码设置4位连续递增，递减的数字或字母');
      } else if(specicalChars.some(char => value.toLowerCase().indexOf(char.toLowerCase()) > -1 )) {
        return Promise.reject('禁止密码设置4位1qaz,2wsx,3edc,dfm,admin,dftc,dfrd,等简单字符');
      }
    }
    return Promise.resolve();
  };

  renderPasswordProgress = () => {
    if (!this.formRef.current) return;
    const form = this.formRef.current;
    const value = form.getFieldValue('password');
    const passwordStatus = this.getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };
  render() {
    const { rdata, visible, firstLogin } = this.props;
    const { update } = this.state;

    return (
      <span>
        <Modal
          title="修改密码"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={600}
          okText="提交"
        >
          <Row style={{ display: 'flex', marginBottom: '10px' }}>
            <Col style={{ width: '20px' }}>
              <InfoCircleOutlined />
            </Col>
            <Col style={{ flex: 1 }}>
            <h4>{`
                账号首次登录/管理员重置密码/当前密码使用时间超过有效期/密码策略变更，
                请先修改密码必须包含大小写字母、数字以及特殊字符(例如^|<>|#%+=~-_…;()$@&"*!?)，长度在 8-12 之间，不允许使用Admin@123等弱密码，且新密码不能和旧密码相同
                `}
                </h4>
            </Col>
          </Row>
          <Form
            ref={this.formRef}
            onFinish={this.handleSubmit}
            labelCol={{ style: { width: '120px' } }}
            wrapperCol={{ span: 18 }}
          >
            {/* {firstLogin ? (
              <FormItem
                label="请填写手机号"
                name={''}
                rules={[
                  {
                    required: true,
                    message: '电话号码有误!',
                    whitespace: true,
                    pattern: /^1[0-9][0-9]\d{8}$/,
                  },
                ]}
              >
                <Input size="large" placeholder="填写手机号" onPressEnter={this.handleOk} />
              </FormItem>
            ) : null} */}
            {/* <FormItem
              label="请输入原始密码"
              name={'oldPassword'}
              rules={[{ required: true, message: '原始密码不能为空' }]}
            >
              <Input
                size="large"
                type="password"
                placeholder="原始密码"
                onPressEnter={this.handleOk}
              />
            </FormItem> */}
            
              <FormItem
                label="新密码"
                name={'password'}
                shouldUpdate
                hasFeedback
                required
                rules={[
                  // {
                  //   required: true,
                  //   message: rdata.pwdStrategyDesc,
                  //   pattern: new RegExp(rdata.pwdStrategy),
                  // },
                  {
                    validator: this.checkPassword,
                  },
                ]}
              >
                <Input.Password
                  size="large"
                  placeholder="请输入新密码"
                  onPressEnter={this.handleOk}
                  // onChange={() => {
                  //   this.setState({ update: !update });
                  // }}
                />
              </FormItem>
            <FormItem
              label="确认新密码"
              name={'confirm'}
              dependencies={['password']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: '请确认密码！',
                },
                ({ getFieldValue }) => {
                  return {
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不匹配！'));
                      },
                    }
                  }
              ]}
            >
              <Input.Password
                size="large"
                placeholder="请确认输入的密码"
                onPressEnter={this.handleOk}
              />
            </FormItem>
          </Form>
        </Modal>
      </span>
    );
  }
}
export default connect(state => ({
  rdata: state.login.pwdStrategy,
  oldPassword: state.login.oldPassword,
}))(updatePassword);
